package hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mysql.jdbc.StringUtils;
import hospital.exception.HospitalException;
import hospital.model.hosp.*;
import hospital.repository.ScheduleRepository;
import hospital.result.ResultCodeEnum;
import hospital.service.DepartmentService;
import hospital.service.DoctorService;
import hospital.service.HospitalService;
import hospital.service.ScheduleService;
import hospital.utils.IntervalTimeUtil;
import hospital.vo.hosp.BookingScheduleRuleVo;
import hospital.vo.hosp.DepartmentVo;
import hospital.vo.hosp.ScheduleOrderVo;
import hospital.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author
 * @description:
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private DoctorService doctorService;

    /**
     * @Author yang
     * @Description //TODO //保存或者修改排班方法
     * @Param [parameterMap]
     * @return
     **/
    @Override
    public void saveOrUpdate(Map<String, Object> parameterMap) {
        //通过Jsonogject parameterMap-> String->Schedule
        String str = JSONObject.toJSONString(parameterMap);
        Schedule schedule = JSONObject.parseObject(str, Schedule.class);

        //判断该对象是否存在
        Schedule scheduleExit=scheduleRepository
                .getScheduleByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(),schedule.getDepcode(),schedule.getHosScheduleId());

        //对象存在，则为修改
        if(null!=scheduleExit){
            schedule.setId(scheduleExit.getId());
            schedule.setCreateTime(scheduleExit.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(scheduleExit.getIsDeleted());
            //保存科室信息
            scheduleRepository.save(schedule);
        }else{ //则为添加
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            //保存科室信息
            scheduleRepository.save(schedule);
        }
    }

    /**
     * @Author yang
     * @Description //TODO
     * @Param [parameterMap]
     * @return
     **/
    @Override
    public Page<Schedule> findSchedule(Map<String, Object> parameterMap) {
        String hoscode = (String) parameterMap.get("hoscode");
        String limitStr= (String) parameterMap.get("limit");
        Integer limit= StringUtils.isNullOrEmpty(limitStr)?1:Integer.parseInt(limitStr);
        String pageStr= (String) parameterMap.get("page");
        Integer page=StringUtils.isNullOrEmpty(pageStr)?1:Integer.parseInt(pageStr);
        //创建分页对象 第一页为0
        PageRequest pageRequest=PageRequest.of(page-1,limit);
        Schedule schedule=new Schedule();
        schedule.setHoscode(hoscode);

        //设置模糊查询规则
        ExampleMatcher matcher=ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> scheduleExample=Example.of(schedule,matcher);
        Page<Schedule> all = scheduleRepository.findAll(scheduleExample, pageRequest);
        return all;
    }

    /**
     * @Author yang
     * @Description //TODO //根据hoscode hosScheduleId 删除科室信息
     * @Param [parameterMap]
     * @return
     **/
    @Override
    public void removeSchedule(Map<String, Object> parameterMap) {
        String hoscode = (String) parameterMap.get("hoscode");
        String hosScheduleId = (String) parameterMap.get("hosScheduleId");
        //获取科室信息
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(null!=schedule){
            //删除科室信息
            scheduleRepository.delete(schedule);
        }
    }

    /**
     * @Author yang
     * @Description //TODO 通过医院编号hoscode和科室编号depcode获取排班规则数据
     * @Param [page, limit, hoscode, depcode]
     * @return
     **/
    @Override
    public Map<String, Object> getScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //1.创建hoscode depcode的匹配规则
        Criteria criteria=Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2.根据工作日workDate进行分组，并且进行降序排序，统计号源
        Aggregation aggregation=Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate").first("workDate").as("workDate").
                //统计号源
                count().as("docCount")
                //统计可预约数量
                .sum("reservedNumber").as("reservedNumber")
                //统计不可预约数量
                .sum("availableNumber").as("availableNumber"),
                //根据workDate，进行降序排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)

        );

        //调用方法，最终实现查询
        AggregationResults<BookingScheduleRuleVo> aggregateResult = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //得到分页数据的集合
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregateResult.getMappedResults();

        //根据工作日workDate进行分组，获取分组的总数量
        Aggregation totalAgg=Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate")
        );

        //获取分组的总数量
        AggregationResults<BookingScheduleRuleVo> totalList = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalList.getMappedResults().size();

        //获取医院的名称
        Hospital hospital = hospitalService.getHospital(hoscode);
        String hosname=null;
        if(null!=hospital){
            hosname = hospital.getHosname();
        }


        int count=0; //当前的总排班数
        //计算当前预约日期对应星期
        for (BookingScheduleRuleVo item:bookingScheduleRuleVoList){
            //进行时间的比较，在当前时间之后的，不在显示
            Date nowDate=new Date();
            Date workDate = item.getWorkDate();

            //如果workDate 晚于当前时间则，保存到列表中
            if(workDate.after(nowDate)){
                System.out.println(workDate +" "+ nowDate);
                String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
                item.setDayOfWeek(dayOfWeek);
                count++;
            }
        }

        //最终将所有数据，进行封装到map中
        Map<String,Object> results=new HashMap<>();
        //分页数据
        results.put("bookingScheduleRuleVoList",bookingScheduleRuleVoList);
        //总数目
//        results.put("total",total);
        results.put("total",count);
        //其他数据
        Map<String,Object> baseMap=new HashMap<>();
        //医院名字
        baseMap.put("hosname",hosname);
        results.put("baseMap",baseMap);
        return results;
    }

    /**
     * @Author yang
     * @Description //TODO 根据医院编号hoscode 科室编号depcode 工作日期workDate查询出排班的详情
     * @Param [hoscode, depcode, workDate]
     * @return
     **/
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {

        //根据医院编号hoscode 科室编号depcode 工作日期workDate查询出排班的详情

        List<Schedule> scheduleList=
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDateTime());


        //封装其他信息：主要为医院名称，科室名称，星期
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });
        return scheduleList;
    }

    /**
     * @Author yang
     * @Description //TODO 获取可预约排班数据
     * @Param [page, limit, hoscode, depcode]
     * @return
     **/
    @Override
    public Map<String, Object> getBookingSchedule(Integer page, Integer limit, String hoscode, String depcode) {
        //通过hoscode，获取医院的预约规则
        Hospital hospital = hospitalService.getHospital(hoscode);
        //如果hospital为空，抛出异常
        if(hoscode==null){
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        //得到医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约日期的数据（分页）
        IPage pageDate=this.getListDate(page,limit,bookingRule);
        //获取可预约日期的数据
        List dateList = pageDate.getRecords();

        //设置匹配条件 当前时间范围内
        Criteria criteria=Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)
                .and("workDate").in(dateList);
        //设置聚合条件，例如分页，求和，分组等
        Aggregation agg=Aggregation.newAggregation(
                //设置匹配条件
                Aggregation.match(criteria),
                //分组字段
                Aggregation.group("workDate").first("workDate").as("workDate").
                //统计号源
                count().as("docCount")
                  //统计可预约数量
                .sum("reservedNumber").as("reservedNumber")
                 //统计不可预约数量
                 .sum("availableNumber").as("availableNumber")
        );

        AggregationResults<BookingScheduleRuleVo> aggregateResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> ScheduleRuleVoResults = aggregateResult.getMappedResults();


        //合并数据  List<BookingScheduleRuleVo> ---> Map<workDate,BookingScheduleRuleVo> 方便读取
        //map集合 key日期  value预约规则和剩余数量等
        Map<Date,BookingScheduleRuleVo> scheduleVoMap=new HashMap<>();
        for(BookingScheduleRuleVo item:ScheduleRuleVoResults){
            Date workDate = item.getWorkDate();
            //无key则进行添加
            scheduleVoMap.put(workDate,scheduleVoMap.getOrDefault(workDate,item));
        }

        //获取可预约排班规则，对可预约排班规则进行完善
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0,len=dateList.size();i<len;i++) {
            Date date = (Date) dateList.get(i);

            //获取当天的可预约规则
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);

            //如果当天没有排班医生
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo=new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }

            //设置可预约日期 "yyyy-MM-dd"
            bookingScheduleRuleVo.setWorkDate(date);
            //设置可预约日期  "MM月dd日"
            bookingScheduleRuleVo.setWorkDateMd(date);
            //设置周几 星期
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(date)));

            //特殊情况
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i==len-1 && page ==pageDate.getPages() ){
                bookingScheduleRuleVo.setStatus(1);
            }else {
                bookingScheduleRuleVo.setStatus(0);
            }

            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1){
                DateTime stopDateTime = this.getDateTime(date, bookingRule.getStopTime());
                //现在时间超过停号时间
                if(stopDateTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        Map<String,Object> result = new HashMap<>();
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", pageDate.getTotal());

        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospital(hoscode).getHosname());
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * @Author yang
     * @Description //TODO 根据排班的id，获取排班的详情
     * 存在一个异常Caused by: java.util.NoSuchElementException: No value present
     * 这个问题通常是由于在使用Java 8新特性Optional<T>时，调用了get()方法，但是Optional实例中并没有任何值，
     * 导致触发NoSuchElementException异常。该异常表示尝试读取值时找不到元素。
     *
     *
     * @Param [scheduleId]
     * @return
     **/
    @Override
    public Schedule getSchedule(String scheduleId) {
        //Schedule schedule = scheduleRepository.findById(scheduleId).get();
        Optional<Schedule> optional = scheduleRepository.findById(scheduleId);
        Schedule schedule =null;
        // 判断是否有值
        if(optional.isPresent()){
            schedule = optional.get();
        }
        return this.packageSchedule(schedule);
    }
    /**
     * @Author yang
     * @Description //TODO 根据排班的 hosScheduleId ,获取排班的详情
     * @Param [scheduleId]
     * @return
     **/
    @Override
    public Schedule getScheduleReceiver(String hosScheduleId) {
        //会导致 取消预约更新预约数MQ刷屏报错
        Schedule schedule = scheduleRepository.getScheduleByHosScheduleId(hosScheduleId);
        return this.packageSchedule(schedule);
    }

    /**
     * @Author yang
     * @Description //TODO 根据排班id获取预约下单数据
     * @Param [scheduleId]
     * @return
     **/
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //根据scheduleId获取排班详情
        Schedule schedule = this.getSchedule(scheduleId);
        if(null==schedule){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        //Schedule的 hoscode，查询医院信息
        Hospital hospital = hospitalService.getHospital(schedule.getHoscode());
        if(null==hospital){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        //获取排班规则
        BookingRule bookingRule = hospital.getBookingRule();
        if(null==bookingRule){
            throw  new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        //封装各种数据
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //医院编号
        scheduleOrderVo.setHoscode(hospital.getHoscode());
        //医院名称
        scheduleOrderVo.setHosname(hospital.getHosname());
        //科室编号
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        //科室名称
        scheduleOrderVo.setDepname(departmentService.getDepName(hospital.getHoscode(), schedule.getDepcode()));
        //排班编号
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        //医生职称
        scheduleOrderVo.setTitle(schedule.getTitle());
        //安排日期
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        //安排时间
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        //医事服务费
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        Date startDate = startTime.toDate();
        scheduleOrderVo.setStartTime(startDate);

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    /**
     * @Author yang
     * @Description //TODO //更新排班的数据 rabbitmq
     * @Param [schedule]
     * @return 
     **/
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * @Author yang
     * @Description //TODO //获取可预约日期的数据（分页）
     *
     * @Param [page, limit, bookingRule]
     * @return
     **/
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //获取当前的放号时间 年月日时分秒
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //得到当前预约周期 ，每个医院的预约周期不同
        Integer cycle = bookingRule.getCycle();

        //如果当前时间，超过了放号时间，可预约的天数延后一天，周期增加1天
        if(releaseTime.isBeforeNow()){
            cycle+=1;
        }
        //DateTime YYYY-MM-DD HH:MM:SS
        //Date --->  yyyy-MM-dd
        //获取可预约所有日期，最后一天显示即将放号
        //用于后面查询指定医院的指定科室的指定天数的排班详情
        List<Date> dateList=new ArrayList<>();
        for(int i=0;i<cycle;i++){
            DateTime dateTime = new DateTime().plusDays(i);
            String date = dateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(date).toDate());
        }

        //将可预约日期进行，分页。因为网页一共显示7条数据
        List<Date> pageDateList=new ArrayList<>();
        //使用MongoDB，进行查询排班数据，使用跳过多少条的方式，进行分页
        int start=(page-1)*limit;
        // 获取可[start，end]内的预约时间
        int end=(page-1)*limit+limit;
        //如果某个医院的医院周期缩短，则可预约时间的天数少于7条，那么可以再一个页面中显示
        if(end>dateList.size()){
            end=dateList.size();
        }
        //为可预约时间，分页
        for(int i=start;i<=end;i++){
            pageDateList.add(dateList.get(i));
        }

        //创建分页的条件  total 返回记录的总数  size 每页显示条数  page  当前页
        IPage<Date>  pageCondition=new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page,7,dateList.size());
        //records  用来存放查询出来的数据
        pageCondition.setRecords(pageDateList);
        return pageCondition;
    }
    /**
     * @Author yang
     * @Description //TODO 格式化时间
     * @Param [schedule]
     * @return
     **/
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString=new DateTime(date).toString("yyyy-MM-dd")+" "+timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
    //封装其他信息：主要为医院名称，科室名称，星期
    private Schedule packageSchedule(Schedule schedule) {
        if(schedule == null){
            return null;
        }
        //封装再params里面
        Map<String, Object> param = schedule.getParam();
        //医院名称
        param.put("hosname",hospitalService.getHospital(schedule.getHoscode()).getHosname());
        //科室名称
        param.put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //星期
        param.put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return  schedule;
    }


    /**
     * @Author yang
     * @Description //TODO 计算当前预约日期对应星期
     * @Param [dateTime]
     * @return
     **/
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * @Author yang 生成合理的排班数据
     * @Description //TODO
     * @Param
     * @return
     **/
    public  List<ScheduleJson> getAllSchedule(String hoscode) {
        //DepartmentService departmentService=new DepartmentServiceImpl();
        //得到所有的部门信息
        List<DepartmentVo> departmentList = departmentService.getDepartmentList(hoscode);
        //DoctorService doctorService=new DoctorServiceImpl();
        // 得到所有的医生的信息
        List<Doctor> doctorList = doctorService.getAllDoctor();

        // 获取有效天数
        List<String> validDays = IntervalTimeUtil.getValidDays();

        // 排班编号
        int hosScheduleId=1;

        // 将生成的JSON字符串写入.json文件中
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("[");
        // 遍历所有的部门
        for(int i=0;i<departmentList.size();i++){
            DepartmentVo departmentVo = departmentList.get(i);
            // 得到子部门的信息，为每一个子部门设置排班信息
            List<DepartmentVo> children = departmentVo.getChildren();
            for (int j = 0; j < children.size(); j++) {
                //设置排班时间
                for (int k = 0; k < validDays.size(); k++) {
                    // 格式化工作时间
                        // 循环设置排班的医生
                        int point = j%doctorList.size();

                        ScheduleJson schedule = new ScheduleJson();
                        schedule.setHoscode(hoscode);// 医院编号
                        schedule.setDepcode(children.get(j).getDepcode()); //部门编号
                        schedule.setTitle(doctorList.get(point).getTitle()); // 医生职称
                        schedule.setDocname(doctorList.get(point).getDocname()); // 医生名称
                        schedule.setSkill(doctorList.get(point).getSkill()); // 医生技能

                        // 设置工作时间
                        schedule.setWorkDate(validDays.get(k));
                        // 设置工作时间是上午还是下午 0上午,1下午如果为偶数则
                        schedule.setWorkTime(k%2);
                        //可预约数
                        schedule.setReservedNumber(50);
                        //剩余预约数
                        schedule.setAvailableNumber(50);
                        schedule.setAmount(new BigDecimal(100));
                        schedule.setStatus(1);

                        //设置排班编号
                        schedule.setHosScheduleId(String.valueOf(hosScheduleId));
                        hosScheduleId++;

                        // 添加到排班结果集中
                        //scheduleList.add(schedule);
                        JSONObject json=(JSONObject)JSONObject.toJSON(schedule);
                        //System.out.println(json);
                        stringBuilder.append(json);
                        if(i==departmentList.size()&&j == children.size() && k == validDays.size()){
                            stringBuilder.append("");
                        }else {
                            stringBuilder.append(",\n");
                        }
                }
            }
        }
        stringBuilder.append("]");
        // 将stringBuilder 写入JSON文件中
        String fileName="service/service_hospital/src/main/resources/schedule1.json";
        try {
            OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8);
            writer.write(stringBuilder.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
